package cool.taomu.toolkit.utils

import cool.taomu.toolkit.utils.inter.ICallback
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStreamReader
import java.util.HashMap
import java.util.Map
import java.util.stream.Collectors
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.SystemUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.LoggerFactory

class CmdLineUtils {
	val static LOG = LoggerFactory.getLogger(CmdLineUtils);

	def static exec(String content, Map<String, String> environment) {
		var Map<String,String> env = new HashMap<String,String>;
		if (environment !== null && environment.size > 0) {
			env = environment.entrySet.stream().collect(Collectors.toMap([it.key], [String.valueOf(it)]));
		}
		val buf = new StringBuffer();
		if (SystemUtils.IS_OS_WINDOWS) {
			var sh = File.createTempFile("taomubox_windows", ".bat");
			LOG.info("执行脚本路径:{}", sh.absolutePath);
			FileUtils.writeStringToFile(sh, content.trim, "UTF-8");
			start("Windows", [
				buf.append(it);
				buf.append("\n");
			], env, sh.absolutePath);
			sh.delete;
		} else {
			var sh = File.createTempFile("taomubox_unix", ".sh");
			LOG.info("执行脚本路径:{}", sh.absolutePath);
			FileUtils.writeStringToFile(sh, content.trim, "UTF-8");
			start("Linux", [
				LOG.info("chmod +x : {}", it);
			], env, "chmod", "+x", sh.absolutePath);
			start("Linux", [
				buf.append(it);
				buf.append("\n");
			], env, "/bin/bash", "-c", sh.absolutePath);
			sh.delete;
		}
		return buf;
	}

	def static void start(String name, ICallback<String> call, Map<String, String> env, String... args) {
		try {
			var ProcessBuilder pb = new ProcessBuilder();
			if (env !== null) {
				pb.environment.putAll(env);
			}
			pb.command(args);
			var Process p = pb.start();
			var BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			var String line;
			while ((line = reader.readLine()) !== null) {
				call.call(line);
			}
			// 等待外部进程完成  
			var int exitVal = p.waitFor();
			if (exitVal == 0) {
				call.call("Success!");
			// processMap.remove(name);
			} else {
				var BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
				while ((line = errorReader.readLine()) !== null) {
					call.call(line);
				}
			}
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
			call.call(ExceptionUtils.getStackTrace(e));
		}
	}
}
